const fs = require('fs');
const OSS = require('ali-oss');
const SparkMD5 = require('spark-md5');

const client = new OSS({
  region: 'oss-cn-hangzhou',
  //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
  accessKeyId: 'LTAI4GDtN8YGDUEAKa316C84',
  accessKeySecret: '5L2Jjn2kcTkviC00pNz3EQqXZxUvWI',

  bucket: 'heruishop'
});


export async function putFile(files, group) {

  let urlPaths = [];
  for (let i = 0; i < files.length; i++) {
    try {
      const md5 = await calculateMd5(files[i]);
      let name = files[i].name;
      var startIndex = name.lastIndexOf(".");
      if (!!group && group.length > 0)
        name = group + "/" + md5+name.substring(startIndex, name.length).toLowerCase();
      let result = await client.put(name, files[i]);

      console.log("result", result);
      urlPaths.push(result.url.replace("http", "https"));
    } catch (err) {
      console.log(err);
    }
  }

  return urlPaths;

}

function calculateMd5(file) {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader(),
      blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice,
      chunkSize = 2097152,
      // read in chunks of 2MB
      chunks = Math.ceil(file.size / chunkSize),
      currentChunk = 0,
      spark = new SparkMD5();

    fileReader.onload = function (e) {
      spark.appendBinary(e.target.result); // append binary string
      currentChunk++;

      if (currentChunk < chunks) {
        loadNext();
      } else {
        resolve(spark.end());
      }
    };

    function loadNext() {
      var start = currentChunk * chunkSize,
        end = start + chunkSize >= file.size ? file.size : start + chunkSize;

      fileReader.readAsBinaryString(blobSlice.call(file, start, end));
    };

    loadNext();
  });
}
